package com.example.demodatajapmapper.service;

import com.example.demodatajapmapper.dao.CustomerRepository;
import com.example.demodatajapmapper.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;


    public Customer save(Customer customer){
        return customerRepository.save(customer);
    }
    public List<Customer> saveAll(List<Customer> customers){
        return customerRepository.saveAll(customers);
    }

    public Page<Customer> findAll(Pageable pageable){
        return customerRepository.findAll(pageable);
    }
    public Customer findByCustomerId(Long customerId){
        return customerRepository.findById(customerId).orElseThrow(
                () -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found")
        );
    }

    public ResponseEntity<?> deleteCustomer(Long customerId){
        return customerRepository.findById(customerId).map(
                customer -> {
                    customerRepository.delete(customer);
                    return ResponseEntity.ok().build();
                }
        ).orElseThrow(() -> new RuntimeException("Customer [customerId=" + customerId + "] can't be found"));
    }

    public ResponseEntity<Customer> updateCustomer(Long customerId, Customer newCustomer){
        return customerRepository.findById(customerId).map(
                customer -> {
                    customer.setCustomerName(newCustomer.getCustomerName());
                    customer.setDateOfBirth(newCustomer.getDateOfBirth());
                    customer.setPhoneNumber(newCustomer.getPhoneNumber());
                    return ResponseEntity.ok(customer);
                }
        ).orElseThrow(() -> new RuntimeException("Customer [customerId" + customerId + "] can't be found"));
    }
}
